package org.dromara.system.controller.system;

import cn.dev33.satoken.annotation.SaCheckPermission;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.web.core.BaseController;
import org.dromara.system.domain.bo.SysFaultInfoBo;
import org.dromara.system.domain.bo.SysFaultInfoQueryBo;
import org.dromara.system.domain.bo.SysFaultManageBo;
import org.dromara.system.domain.bo.SysSolutionDocBo;
import org.dromara.system.domain.vo.SysFaultInfoVo;
import org.dromara.system.domain.vo.SysSolutionDocVo;
import org.dromara.system.service.ISysFaultInfoService;
import org.dromara.system.service.ISysSolutionDocService;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;

/**
 * 故障信息管理（管理端） 控制层
 *
 * @author system
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/fault")
public class SysFaultManageController extends BaseController {

    private final ISysFaultInfoService faultInfoService;
    private final ISysSolutionDocService solutionDocService;

    // ==================== 故障信息管理 ====================

    /**
     * 查询故障信息列表（管理端查看）
     */
    @GetMapping("/list")
    public TableDataInfo<SysFaultInfoVo> list(SysFaultInfoQueryBo queryBo, PageQuery pageQuery) {
        return faultInfoService.queryPageList(queryBo, pageQuery);
    }

    /**
     * 导出故障信息列表（需要权限控制）
     */
    @SaCheckPermission("system:fault:export")
    @Log(title = "故障信息管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(SysFaultInfoQueryBo queryBo, HttpServletResponse response) {
        List<SysFaultInfoVo> list = faultInfoService.queryList(queryBo);
        ExcelUtil.exportExcel(list, "故障信息", SysFaultInfoVo.class, response);
    }

    /**
     * 获取故障信息详情
     */
    @GetMapping("/{faultId}")
    public R<SysFaultInfoVo> getInfo(@NotNull(message = "故障ID不能为空") @PathVariable Long faultId) {
        return R.ok(faultInfoService.queryById(faultId));
    }

    /**
     * 新增故障信息（一体化管理：故障信息 + 解决方案）
     */
    @SaCheckPermission("system:fault:add")
    @Log(title = "故障信息管理", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<SysFaultInfoVo> add(@RequestPart("fault") @Validated(AddGroup.class) SysFaultManageBo faultManage,
                              @RequestPart(value = "files", required = false) MultipartFile[] files) {
        SysFaultInfoVo vo = faultInfoService.createFaultWithSolution(faultManage, files);
        return R.ok(vo);
    }

    /**
     * 修改故障信息（一体化管理：故障信息 + 解决方案）
     */
    @SaCheckPermission("system:fault:edit")
    @Log(title = "故障信息管理", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<SysFaultInfoVo> edit(@RequestPart("fault") @Validated(EditGroup.class) SysFaultManageBo faultManage,
                              @RequestPart(value = "files", required = false) MultipartFile[] files) {
        SysFaultInfoVo vo = faultInfoService.updateFaultWithSolution(faultManage, files);
        return R.ok(vo);
    }

    /**
     * 删除故障信息（一体化管理：联动删除解决方案）
     */
    @SaCheckPermission("system:fault:remove")
    @Log(title = "故障信息管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{faultIds}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空") @PathVariable Long[] faultIds,
                        @RequestParam(defaultValue = "auto") String cascadeStrategy) {
        return toAjax(faultInfoService.deleteFaultWithCascade(Arrays.asList(faultIds), cascadeStrategy));
    }

    // ==================== 注意：级联查询功能已统一到用户端 /user/fault/models|parts|symptoms ====================
    // 管理端可直接调用用户端API，避免代码重复

    // ==================== 级联查询接口（委托给用户端） ====================
    
    /**
     * 获取所有挖掘机机型列表
     */
    @GetMapping("/models")
    public R<List<String>> getExcavatorModels() {
        List<String> models = faultInfoService.getExcavatorModelList();
        return R.ok(models);
    }

    /**
     * 根据机型获取故障部分列表
     */
    @GetMapping("/parts")
    public R<List<String>> getFaultParts(@RequestParam(required = false) String excavatorModel) {
        List<String> parts = faultInfoService.getFaultPartList(excavatorModel);
        return R.ok(parts);
    }

    /**
     * 根据机型和故障部分获取故障现象列表
     */
    @GetMapping("/symptoms")
    public R<List<String>> getFaultSymptoms(@RequestParam(required = false) String excavatorModel,
                                           @RequestParam(required = false) String faultPart) {
        List<String> symptoms = faultInfoService.getFaultSymptomList(excavatorModel, faultPart);
        return R.ok(symptoms);
    }

    // ==================== 解决方案文档独立管理（仅用于特殊场景） ====================

    /**
     * 查询解决方案文档列表（供选择关联）
     */
    @GetMapping("/doc/list")
    public TableDataInfo<SysSolutionDocVo> docList(SysSolutionDocBo queryBo, PageQuery pageQuery) {
        return solutionDocService.queryPageList(queryBo, pageQuery);
    }

    /**
     * 获取解决方案文档详情
     */
    @GetMapping("/doc/{docId}")
    public R<SysSolutionDocVo> getDocInfo(@NotNull(message = "文档ID不能为空") @PathVariable Long docId) {
        return R.ok(solutionDocService.queryById(docId));
    }

    /**
     * 预览解决方案主PDF
     */
    @GetMapping("/doc/preview/{docId}")
    public void previewDoc(@PathVariable Long docId, 
                          @RequestParam(defaultValue = "inline") String disposition,
                          HttpServletResponse response) throws Exception {
        solutionDocService.previewDocument(docId, disposition, response);
    }
}
